package com.kdg.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by kong on 2017/8/14.
 * 1.两个同步方法,一个对象    one  two
 * 2.两个同步方法,两个对象    two  one
 * 3.一个静态同步方法,一个非静态同步方法    two  one
 * 4.两个静态同步方法     one  two
 * 5.一个普通方法,两个同步方法   five one two
 *
 * summary: 静态同步方法的锁是类Number.class; 非静态同步方法的锁是this
 *          同一时刻只能有一个线程持有一把锁   无论几个方法
 */
public class TestThread8Lock {
    public static void main(String[] args) {
        Number number = new Number();
        Number number2 = new Number();
        new Thread(new Runnable() {
            @Override
            public void run() {
                number.printOne();
//                number.printThree();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                number.printTwo();
//                number2.printFour();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                number.printFive();
//                number2.printFour();
            }
        }).start();
    }
}

class Number{

    private Lock lock = new ReentrantLock();

    public synchronized void printOne(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"---one");
    }

    public synchronized void printTwo(){
        System.out.println(Thread.currentThread().getName()+"---two");
    }

    public void printFive(){
        System.out.println(Thread.currentThread().getName()+"---five");
    }

    public void printThree(){
        lock.lock();
        try {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"---three");
        } finally {
            lock.unlock();
        }
    }

    public void printFour(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"---four");
        } finally {
            lock.unlock();
        }

    }
}
